<template>
  <el-drawer
    v-bind="$attrs"
    v-model="visible"
    class="k-drawer-box"
    :append-to-body="true"
    :size="sizeMap[props.width] ? sizeMap[props.width] : width"
    :title="title"
    direction="rtl"
    :before-close="onClickCancel"
  >
    <el-scrollbar>
      <div v-loading="props.contentLoading" class="drawer-content">
        <slot></slot>
      </div>
    </el-scrollbar>
    <template v-if="props.showFooter" #footer>
      <slot name="footer">
        <div class="dialog-footer">
          <el-button v-if="props.showCancelBtn" :disabled="loading" @click="onClickCancel">{{ props.cancelText }}</el-button>
          <el-button v-if="props.showConfirmBtn" :loading="loading" :disabled="confirmDisabled" type="primary" @click="onClickSubmit">{{ props.confirmText }}</el-button>
        </div>
      </slot>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
import { ref, computed } from 'vue';
defineOptions({ name: 'KDrawer' });
interface Props {
  modelValue?: boolean;
  loading?: boolean;
  contentLoading?: boolean;
  title?: string;
  width?: string;
  showFooter?: boolean;
  showCancelBtn?: boolean;
  showConfirmBtn?: boolean;
  beforeClose?: any;
  cancelText?: string;
  confirmText?: string;
  /** 按钮是否禁用，用于禁用表单确认按钮 */
  confirmDisabled?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  contentLoading: false,
  loading: false,
  title: '',
  width: '40%',
  showFooter: true,
  showCancelBtn: true,
  showConfirmBtn: true,
  beforeClose: null,
  cancelText: '取消',
  confirmText: '确定',
  confirmDisabled: false
});
const sizeMap: Record<string, any> = ref({
  xs: '350px',
  small: '500px',
  middle: '640px',
  large: '800px'
});
const emits = defineEmits(['submit', 'cancel', 'update:model-value']);

const visible = computed({
  get: () => {
    return props.modelValue;
  },
  set: (val: boolean) => {
    emits('update:model-value', val);
  }
});

const onClickSubmit = () => {
  emits('submit');
};
const onClickCancel = async () => {
  if (props.loading) return;
  if (typeof props.beforeClose === 'function') await props.beforeClose();
  emits('cancel');
};
</script>

<style lang="scss" scoped>
.drawer-content {
  max-height: calc(100vh - 122px);
}
</style>
<style lang="scss">
.k-drawer-box {
  min-width: 400px;

  .el-drawer {
    &__header {
      padding-bottom: 20px;
      margin-bottom: 0;
      border-bottom: 1px solid #dcdfe6;
    }

    &__footer {
      padding-top: 20px;
      border-top: 1px solid #dcdfe6;
    }
  }
}
</style>
